#![allow(dead_code)]
use rayon::prelude::*;
use std::thread;

/// 并行修改数组数据
fn par_iter_mut(){
    let mut arr = [0, 7, 9, 11];
    // 将数组转成并行可变的迭代器，并遍历修改数组的值
    arr.par_iter_mut().for_each(|p| {
        println!("{:?}", thread::current().id());
        *p -= 1
    });
    println!("{:?}", arr);
}

fn any_all(){
    let vec = vec![2, 4, 6, 8];
    // 并行检查迭代器的任意元素是否与断言匹配
    let _b = vec.par_iter().any(|n| (*n % 2) != 0);
    // 并行检查迭代器的所有元素是否与断言匹配
    let _b = vec.par_iter().all(|n| (*n % 2) == 0);
    
}

/// 并行查询集合中的元素，并返回第一个满足条件的元素
fn find_any() {
    let v = vec![6, 2, 1,  3, 8, 9, 11];

    let f1 = v.par_iter().find_any(|x| {
        println!("{}", **x);
        **x == 9
    });
    let f2 = v.par_iter().find_any(|&&x| x % 2 == 0 && x > 6);
    let f3 = v.par_iter().find_any(|&&x| x > 8);

    println!("{:?}", f1);
    println!("{:?}", f2);
    println!("{:?}", f3);
}

/// vec不稳定排序
fn par_sort() {
    let mut vec = vec![1, 3, 5, 9, 6, 2, 7];
    vec.par_sort_unstable();
    println!("{:?}", vec);
    vec.par_sort_unstable_by(|a, b | b.cmp(a));
    println!("{:?}", vec);
}

struct Person {
    age: u32,
}

/// 并行计算
fn map_reduc() {
    let v: Vec<Person> = vec![
        Person { age: 23 },
        Person { age: 19 },
        Person { age: 42 },
        Person { age: 17 },
        Person { age: 17 },
        Person { age: 31 },
        Person { age: 30 },
    ];

    let num_over_30 = v.par_iter().filter(|&x| x.age > 30).count() as f32;
    let sum_over_30 = v.par_iter()
        .map(|x| x.age)
        .filter(|&x| x > 30)
        .reduce(|| 0, |x, y| x + y);

    let alt_sum_30: u32 = v.par_iter()
        .map(|x| x.age)
        .filter(|&x| x > 30)
        .sum();

    let avg_over_30 = sum_over_30 as f32 / num_over_30;
    let alt_avg_over_30 = alt_sum_30 as f32/ num_over_30;

    assert!((avg_over_30 - alt_avg_over_30).abs() < f32::EPSILON);
    println!("The average age of people older than 30 is {}", avg_over_30);
}
fn main() {
    map_reduc();
}


